/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package expenseslist;

import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JSpinner;

/**
 *
 * @author trunghpb
 */
public class MySqlDb {
    private static MySqlDb myDb;
    
    public static MySqlDb create(){
        if (myDb == null){
            myDb = new MySqlDb();
        }
        return myDb;
    }
    
     public MySqlDb connect() throws Exception{
        if (conn == null){        
            try{
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/money";

            conn = (Connection) DriverManager.getConnection(url, "root", "root");
            return this;
            }catch (Exception ex){
                throw ex;
            }
        }
        return this;
    }
    
    public ResultSet getResult(String sql) throws SQLException{
        Statement stmt = (Statement) conn.createStatement();
        return (ResultSet) stmt.executeQuery(sql);
    }
    
    public PreparedStatement getPrepareStatement(String sql) throws SQLException{
        return conn.prepareStatement(sql);
    }
    
    public static int getRowCount(ResultSet rs) throws SQLException{
        int count = 0;
        int currentRow = rs.getRow();
        
        count = rs.last() ? rs.getRow() : 0;
        
        if (currentRow == 0){
            rs.beforeFirst();
        }else{
            rs.absolute(currentRow);
        }
        return count;
    }
    
    public boolean execute(String sql) throws SQLException{
        Statement stmt = (Statement) conn.createStatement();
        return stmt.execute(sql);
    }

    public boolean execute(PreparedStatement statement) throws SQLException{
        return statement.execute();
    }
    
    public void close() throws SQLException{
        conn.close();
    }
    
    private static Connection conn;
    private PreparedStatement prepareStatement;
}
